from .base_command import BaseCommand
from cleo.helpers import option
from tjob.meta import JobManger
from tjob.handler import PAIHandler
from tjob.handler.cloud_handler import CloudHandler, get_cloud_default_conf


class ShowCommand(BaseCommand):
    name = "show"
    description = "Show relative infos in tjob."
    options = [
        option(
            "platform",
            "p",
            flag=False,
            description="Which platfrom you want to query your job? [pai, local, cloud]",
            default="pai",
        ),
        option(
            "cloud_cluster",
            flag=False,
            description="cloud cluster, default to job-k8s-cluster-sscz, only support in cloud",
            default=None,
        ),
        option(
            "name",
            flag=False,
            description="the job name, only support in cloud",
            default=None,
        ),
        option(
            "jobs",
            "j",
            flag=True,
            description="current running jobs in record."
            + "NOTE: they might stop already",
        ),
        option(
            "nodes",
            flag=True,
            description="current node status.",
        ),
    ]

    def handle(self) -> int:
        if self.option("jobs"):
            platform = self.option("platform").lower()
            self.blue_text(f"Show job of {platform} platform")

            if platform.lower() == "cloud":
                # for each job's params:  cmd > pyfile > init.params
                cloudCluster = self.option("cloud_cluster") or None
                if not cloudCluster:
                    default_conf = get_cloud_default_conf()
                    cloudCluster = default_conf["cloudCluster"]
                name = self.option("name")

                ch = CloudHandler()
                jobJson = ch.show(cloudCluster, name)
                if not jobJson["status"]:
                    raise ValueError(f"Empty job status!")
                jobStatus = jobJson["status"]["state"]["phase"]
                self.red_text(f"Job: {name}, status: {jobStatus}")

            job_manger = JobManger()
            for job_name, job_info in job_manger.jobs.items():
                if not self.option("verbose"):
                    try:
                        job_info["command"] = job_info["command"][:10] + " ... "
                        job_info["dlc_params"]["command"] = (
                            job_info["dlc_params"]["command"][:10] + " ... "
                        )
                    except Exception:
                        pass

                self.blue_text(f"<w> {job_name}  <info> {job_info} <w>\n ")
        if self.option("nodes"):
            PAIHandler.show_node_status()

        if not self.option("verbose"):
            self.green_text("[Hint] Use -v to show MORE content")
